import {
  ds
} from "../../../tools/data"

Page({
  data: {
    action: 'new',
    id: '',
    item: {},
    errMsg: "",
    files: []
  },
  async init() {
    const that = this

    // if(this.data.action == 'edit') {
    //   const swiper = ds.coll('swiper')
    //   swiper.where({
    //     _id: ds.cmd.eq(that.data.id)
    //   }).get({
    //     success: function(res) {
    //       that.setData({item: res.data[0]})
    //     }
    //   });
    // }
  },
  submitClick() {
    // console.log(this.data.files)
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.imgUploaded(this.data.files);
    wx.navigateBack({
      delta: 1
    })
  },
  chooseMediaClick() {
    const that = this
    // console.log("choose")
    wx.chooseMedia({
      success: (chooseResult) => {
        const tempFile = chooseResult.tempFiles[0].tempFilePath;
        // console.log(chooseResult)
        const fileName = tempFile.substr(tempFile.lastIndexOf('/') + 1)
        wx.cloud.uploadFile({
          cloudPath: fileName,
          filePath: tempFile, // 文件路径
        }).then(res => {
          // console.log(res)
          that.data.files.push(res.fileID)
          that.setData({
            files: that.data.files
          });
          that.insert2files(res.fileID)
        })
      },
    });
  },
  delImg(e) {
    const fileId = e.target.dataset.file
    const that = this
    // console.log(e.target.dataset.file)
    wx.showModal({
      title: '提示',
      content: '是否删除点击的图片？',
      success: function (res) {
        if (res.confirm) {
          wx.cloud.deleteFile({
            fileList: [fileId]
          }).then(res => {
            const idx = that.data.files.indexOf(fileId);
            if (idx > -1) that.data.files.splice(idx, 1);
            that.setData({
              files: that.data.files
            })
            that.delFromFiles(fileId)
          }).catch(error => {
            wx.showToast({
              title: '删除失败',
              icon: 'fail',
              duration: 1000,
              mask: true
            })
          })

        }
      }
    })
  },
  insert2files(fileId) {
    const swiper = ds.coll('files')
    swiper.add({
      data: {
        fileId: fileId,
      },
      success: function (res) {
        // console.log(res)
      }
    });
  },
  delFromFiles(fileId) {
    const swiper = ds.coll('files')
    swiper.where({
      fileId: fileId
    }).remove();
  },
  onLoad(option) {
    if (option.action) {
      this.setData({
        action: option.action,
        id: option.id
      })
    }
    this.init(true);
  },
});